import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

class Demo1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Page1(),
    );
  }
}

class Page1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // int show(){   //同步
    //   return 12;
    // }
    //
    // print(show());

    //错的——build必须是同步的
    // Future<int> show()async{  //异步
    //   return 12;
    // }
    //
    // var res=await show();
    // print(res);

    // show().then((val){
    //   print(val);
    // });

    final controller = TextEditingController();

    return Scaffold(
      appBar: AppBar(title: Text('测试')),
      body: Column(children: [
        TextField(
          keyboardType: TextInputType.multiline,
          controller: controller,
          minLines: 5,
          maxLines: 10,
        ),
        FlatButton(
          child: Text('保存'),
          color: Colors.blue,
          onPressed: () async {
            //1.拼凑合法路径
            var dir =
                await getTemporaryDirectory().timeout(Duration(seconds: 1));

            //2.构建File对象
            var file = File('${dir.path}/b.txt');

            //3.写入文件
            var content = utf8.encode(controller.value.text);
            await file.writeAsBytesSync(content);

            print('success');

            //4.读取文件
            try {
              var res = await file.readAsBytesSync();
              var str2 = utf8.decode(res);
              print(str2);
            } catch (err) {
              print(err.toString());
            }
          },
        ),
      ]),
    );
  }
}
